package com.zkadmin.controller;

import org.apache.shiro.SecurityUtils;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Button;
import org.zkoss.zul.Tree;
import org.zkoss.zul.Window;

import com.zkadmin.renderer.ResourceTreeitemRenderer;
import com.zkadmin.service.SysResourceService;
import com.zkadmin.util.AdminConstants;
import com.zkadmin.util.AdminWebUtils;

@SuppressWarnings("serial")
public class ResourceListCtrl extends BaseCtrl<Window> {

	@WireVariable
	private SysResourceService sysResourceService;

	private Window win;

	@Wire
	private Tree resourceTree;

	@Wire
	private Button createResourceBtn;

	@Override
	protected void init(Window win) {
		this.win = win;
		if (!SecurityUtils.getSubject().hasRole(AdminConstants.ROLE_ADMIN)) {
			createResourceBtn.setDisabled(!SecurityUtils.getSubject().isPermitted("sys:resource:create"));
		}

		resourceTree.setItemRenderer(new ResourceTreeitemRenderer(this, sysResourceService));
		refreshData();
	}

	public void refreshData() {
		resourceTree.setModel(sysResourceService.getResourceTreeModel(false));
	}

	@Listen("onClick = #createResourceBtn")
	public void showCreateDialog(Event e) {
		Window window = (Window) Executions.createComponents(AdminWebUtils.getZulPagePath("admin/create_resource_dialog.zul"), win, null);
		window.addEventListener(AdminConstants.EVENT_ONREFRESH, new EventListener<Event>() {
			@Override
			public void onEvent(Event event) throws Exception {
				refreshData();
			}
		});
		AdminWebUtils.eventAddCaption(window, e);
		window.doModal();
	}

	@Listen("onClick = #resourceTreeBtn")
	public void showEditMenuTreeDialog(Event e) {
		Window window = (Window) Executions.createComponents(AdminWebUtils.getZulPagePath("admin/edit_resource_tree_dialog.zul"), win, null);
		window.addEventListener(AdminConstants.EVENT_ONREFRESH, new EventListener<Event>() {
			@Override
			public void onEvent(Event event) throws Exception {
				refreshData();
			}
		});
		AdminWebUtils.eventAddCaption(window, e);
		window.doModal();
	}
}
